package com.ysd.utils;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

public class ExcelUtil {
    public static XSSFWorkbook createExcel(String[] title, List<List<String>> dataList, String sheetName) {
        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(sheetName);
        Row head = sheet.createRow(0);
        //设置表头
        for (int i = 0; i < title.length; i++) {
            Cell cell = head.createCell(i);
            cell.setCellValue(title[i]);
        }
        //设置数据
        for (int i = 0; i < dataList.size(); i++) {
            Row body = sheet.createRow(i + 1);
            for (int j = 0; j < dataList.get(i).size(); j++) {
                Cell cell = body.createCell(j);
                cell.setCellValue(dataList.get(i).get(j));
            }
        }
        return workbook;
    }

    public static void exportExcel(Workbook workbook, String fileName, String exportPath) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(exportPath + fileName + ".xlsx");
            workbook.write(out);
            out.flush();
            System.out.println("导出成功");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null) {
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileName != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

